<?php 
	class BlogAction extends CommonAction{
		public function index(){
			import('ORG.Util.Page');
			$type=$_GET['type']?$_GET['type']:0;
			$this->type=$type;
			$count=M('Blog')->where(array('del'=>$type))->count();
			$page=new Page($count,10);
			$limit=$page->firstRow.','.$page->listRows;
			
			$this->blog=D('BlogRelation')->getBlogs($limit,$type);
			$this->page=$page->show();
			$this->display();
		}

		//发布/修改博文视图
		public function blog(){
			$id=$_GET['id']?$_GET['id']:0;
			$blog=D('BlogRelation')->getBlog($id);
			$this->blog=$blog;

			$this->cate=M('cate')->order('sort')->field(array('id','name'))->select();

			$this->attr=M('attr')->select();
			$this->display();
		}

		//发布博文表单处理
		public function addBlog(){
			$pid=(int)$_POST['id'];
			$blog=$pid?array('id'=>$pid):array();
			$data=array(
				'title'=>$_POST['title'],
				'summary'=>strip_tags($_POST['summary']?$_POST['summary']:$_POST['content']),
				'content'=>$_POST['content'],
				'cid'=> (int)$_POST['cid'],
				'time' =>time(),
				);
			$blog=array_merge($blog,$data);
			if($id=$pid?M('blog')->save($blog):M('blog')->add($blog)){
				$data=array();
				foreach ($_POST['aid'] as $value) {
					$flag=$_POST['id']?!in_array($value,$_POST['attr']):true;
					if($flag){
						$data['aid']=$value;
						$data['bid']=$pid;
						M('blog_attr')->add($data);
					}
				}
				if($_POST['id']){
					foreach ($_POST['attr'] as  $v) {
						if(!in_array($v,$_POST['aid']))
						M('blog_attr')->where(array('aid'=>$v,'bid'=>$_POST['id']))->delete();
					}
				}
				$this->success('发布成功!',U(GROUP_NAME.'/Blog/index'));
			}else {
				$this->error('发布失败!');
			}
		}

		//添加到回收站或还原
		public function toRecycle(){
			$data=array(
				'id'=>$_GET['id'],
				'del'=>(int)$_GET['del']
				);
			$msg=$_GET['del']?"删除":'还原';
			if(M('blog')->save($data)) $this->success($msg.'成功!',U(GROUP_NAME.'/Blog/index'));
			else $this->error($msg.'失败!');
		}

		public function delete(){
			$id=$_GET['id'];
			if(M('blog')->delete($id)){
				$this->success("删除成功!",U(GROUP_NAME.'/Blog/index',array('type'=>1)));
			}else $this->error("删除失败!");
		}

		//清空回收站
		public function clear(){
			if(M('blog')->where(array('del'=>1))->delete())$this->success('清空成功!',U(GROUP_NAME.'/Blog/index',array('type'=>1)));
			else $this->error('清空失败!');
		}
	}



